﻿using System;
using System.IO;

namespace Microsoft.WowAddonStudio.Project.Import.Folder
{
	public enum ImportLocationValidationResult
	{
		NOSOURCEDIR = 0,
		NOTOC,
		MULTIPLETOC,
		VALID
	} ;

	public enum ImportTargetValidationResult
	{
		ALREADYEXISTS = 0,
		VALID
	} ;

	/// <summary>
	/// Validates folder import settings. The two basic validations currently in use are:
	///		1. Validate import location (existance, and toc file)
	///		2. Validate target location (existance, and 
	/// </summary>
	public static class FolderImportSettingsValidator
	{
		/// <summary>
		/// Validates import location. Checks whether the folder exists, and if it contains a single TOC
		/// file.
		/// </summary>
		public static ImportLocationValidationResult ValidateImportLocation(string importLocation)
		{
			if (!Directory.Exists(importLocation))
				return ImportLocationValidationResult.NOSOURCEDIR;

			string[] tocFiles = Directory.GetFiles(importLocation, "*.toc");

			if (tocFiles == null || tocFiles.Length == 0)
				return ImportLocationValidationResult.NOTOC;

			if (tocFiles.Length > 1)
				return ImportLocationValidationResult.MULTIPLETOC;

			return ImportLocationValidationResult.VALID;
		}

		/// <summary>
		/// Validates target location. Checks whether the folder exists, and no subfolder with the name
		/// of the TOC file exists.
		/// </summary>
		public static ImportTargetValidationResult ValidateTargetLocation(string sourceLocation,
		                                                                  string targetLocation)
		{
			string tocPath = GetFirstTocFilePath(sourceLocation);
			string targetPath = Path.Combine(targetLocation, Path.GetFileNameWithoutExtension(tocPath));

			if (Directory.Exists(targetPath))
				return ImportTargetValidationResult.ALREADYEXISTS;

			return ImportTargetValidationResult.VALID;
		}

		/// <summary>
		/// Gets the first toc file path.
		/// </summary>
		/// <param name="importLocation">The import location.</param>
		/// <returns></returns>
		public static string GetFirstTocFilePath(string importLocation)
		{
			string[] tocFiles = Directory.GetFiles(importLocation, "*.toc");

			if (tocFiles == null || tocFiles.Length == 0)
				throw new ApplicationException("No toc file found.");

			return tocFiles[0];
		}
	}
}